//
//  EFAMoreVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMoreVC.h"
#import "EFAMoreTCell.h"
#import "EFAMoreTitleCell.h"
#import <UIImageView+WebCache.h>
#import "EFAMoreInfoVC.h"
#import "EFASettingVC.h"
#import "EFAAboutUsVC.h"
#import "EFAModel.h"
#import "ApiManager.h"
#import "EFAMoreNameVC.h"

@interface EFAMoreVC ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *dataArray;

@end

static NSString *const kReuseCellId = @"EFAMoreTCell";
static NSString *const kReuseCellId2 = @"EFAMoreTitleCell";

@implementation EFAMoreVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshWholeView];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"更多";
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    UINib *nib2 = [UINib nibWithNibName:kReuseCellId2 bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
     [self.tableView registerNib:nib2 forCellReuseIdentifier:kReuseCellId2];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.separatorStyle = UITableViewCellEditingStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
    ///< 主要是为了刷新用户角色
    [self requestRefreshUserInfo];
}

//页面显示在前端的时候执行
- (void)viewDidAppear:(BOOL)animated{
    [self dataArray:YES];
    [self.tableView reloadData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
         EFAMoreTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId2 forIndexPath:indexPath];
        NSDictionary *dic = self.dataArray[indexPath.section];
        NSString *headerImgUrl = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_headimg_url;
         cell.backgroundColor =  [UIColor colorWithPatternImage:[UIImage imageNamed:@"icon_header_bg"]];
        [cell.headerImgView sd_setImageWithURL:[NSURL URLWithString:(headerImgUrl ? headerImgUrl : @"")]
                                placeholderImage:[UIImage imageNamed:dic[@"imgName"]]];
        cell.nameLabel.text = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname;
        cell.phoneLabel.text = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_phonenumber;
        return cell;
    } else if(indexPath.section < self.dataArray.count) {
        EFAMoreTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        cell.upLabel.hidden = YES;
        cell.nameLabel.hidden = NO;
        cell.bottomLabel.hidden = YES;
        if(indexPath.section == 3 || indexPath.section == 5){
            cell.rightLabel.hidden = YES;
            cell.RightArrowImg.hidden = YES;
        }else{
            cell.rightLabel.hidden = NO;
            cell.RightArrowImg.hidden = NO;
        }
        cell.backgroundColor = [UIColor whiteColor];
        NSDictionary *dic = self.dataArray[indexPath.section];
        cell.portraitImgView.image = [UIImage imageNamed:dic[@"imgName"]];
        cell.nameLabel.text = dic[@"title"];
        cell.rightLabel.text = dic[@"subTitle"];
        return cell;
    }
    return nil;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(section == 6){
        return 8;
    }
    return 0.000001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(section == 0){
        return 8;
    }
    return 0.5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(section  > 0){
        UIView *footerView = [[UIView alloc] init];
        footerView.backgroundColor = [UIColor whiteColor];
        UIView *cfView = [[UIView alloc]init];
        cfView.backgroundColor = ColorFromRGB(0xDDDDDD);
//        cfView.layoutMargins = UIEdgeInsetsMake(0, 15, 0, 0);
        [footerView addSubview:cfView];
        cfView.sd_layout.leftSpaceToView(footerView, 15).rightSpaceToView(footerView, 0).topSpaceToView(footerView, 0).bottomSpaceToView(footerView, 0);
        return footerView;
    }
    return nil;
}


- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return @" ";
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section < self.dataArray.count) {
        NSDictionary *dic = self.dataArray[indexPath.section];
        return [dic[@"rowHeight"] floatValue];
    }
    return 50.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {           //!< 个人资料
        [self jumpToPersonalInfo];
    }else if(indexPath.section == 1){ //单位名称
          [self jumpToEditCompany];
    }else if(indexPath.section == 2){//单位地址
         [self jumpToEditCompanyAddress];
    }else if(indexPath.section == 3){//联系电话
        
    }else if(indexPath.section == 4){//联系邮箱
         [self jumpToEditEmail];
    }else if(indexPath.section == 5){//设备供应商
        
    }else if(indexPath.section == 6){//关于我们
        [self jumpToAboutUs];
    }
    
   
    //    else if (indexPath.section == 2) {    //!< 设置
//        [self jumpToSetting];
//    }
}




- (void)jumpToEditCompany {
    EFAMoreNameVC *vc = [[EFAMoreNameVC alloc] init];
    vc.curType = EFAMoreNameTypeCompany;
    [self showViewController:vc sender:nil];
}

- (void)jumpToEditCompanyAddress {
    EFAMoreNameVC *vc = [[EFAMoreNameVC alloc] init];
    vc.curType = EFAMoreNameTypeCompanyAddress;
    [self showViewController:vc sender:nil];
}

- (void)jumpToEditEmail {
    EFAMoreNameVC *vc = [[EFAMoreNameVC alloc] init];
    vc.curType = EFAMoreNameTypeEmail;
    [self showViewController:vc sender:nil];
}

#pragma mark - event response
#pragma mark - private methods
- (void)jumpToPersonalInfo {
    EFAMoreInfoVC *vc = [[EFAMoreInfoVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)jumpToAboutUs {
    [self getConfigInfo];
}
- (void)jumpToSetting {
    EFASettingVC *vc = [[EFASettingVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)refreshWholeView {
    [self.tableView reloadData];
}
#pragma mark - network request
- (void)requestRefreshUserInfo {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineUserCenter] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求用户信息返回：%@", responseObject);
        [[EFAModel sharedInstance] refreshUserInfoWithDictionary:responseObject];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求用户信息失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


#pragma mark - network request
- (void)getConfigInfo{
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiUserConfig] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求用户信息返回：%@", responseObject);
        EFAAboutUsVC *vc = [[EFAAboutUsVC alloc] init];
        NSDictionary *datas = [responseObject valueForKey:@"result"];
//        int  isSms =  (int)datas[@"efairyuserconfig_is_sms"];
//        int  isApp =  (int)datas[@"efairyuserconfig_is_app"];
//        int  isVoice = (int)datas[@"efairyuserconfig_is_voice"];
        vc.smsIsNotice  = [datas[@"efairyuserconfig_is_sms"] boolValue];//是否开启短信提醒
        vc.tuisongIsNotice = [datas[@"efairyuserconfig_is_app"] boolValue];//是否开启推送
        vc.phoneIsNotice = [datas[@"efairyuserconfig_is_voice"] boolValue];//是否开启电话语音播报
        [self showViewController:vc sender:nil];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求用户信息失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (NSArray *)dataArray:(BOOL)isRefresh{
    if (!_dataArray || isRefresh) {
        EFALoginUserInfo *userInfo = [EFAModel sharedInstance].loginInfo.user_info;
        NSString *company = userInfo.efairyuser_company ? userInfo.efairyuser_company : @"";
        NSString *address = userInfo.efairyuser_company_address ? userInfo.efairyuser_company_address : @"";
        NSString *phone = userInfo.efairyuser_phonenumber ? userInfo.efairyuser_phonenumber : @"";
        NSString *email = userInfo.efairyuser_email ? userInfo.efairyuser_email : @"";
        NSString *supplier = userInfo.efairyuser_device_supplier ? userInfo.efairyuser_device_supplier : @"";
        _dataArray = @[@{@"imgName" : @"icon_header",
                         @"title" : @"德派森",
                         @"rowHeight" : @(132)},
                       @{@"title" : @"单位名称",
                         @"subTitle" : company,
                         @"imgName" : @"icon_corporate_name",
                         @"rowHeight" : @(45),
                         @"arrow" : @(YES)},
                       @{@"title" : @"单位地址",
                         @"subTitle" : address,
                         @"imgName" : @"icon_corporate_address",
                         @"rowHeight" : @(45),
                         @"arrow" : @(YES)},
                       @{@"title" : @"联系电话",
                         @"subTitle" : phone,
                         @"imgName" : @"icon_phone_number",
                         @"rowHeight" : @(45),
                         @"arrow" : @(NO)},
                       @{@"title" : @"联系邮箱",
                         @"subTitle" : email,
                         @"imgName" : @"icon_email",
                         @"rowHeight" : @(45),
                         @"arrow" : @(YES)},
                       @{@"title" : @"设备供应商",
                         @"imgName" : @"icon_device_supplier",
                         @"subTitle" : supplier,
                         @"rowHeight" : @(45),
                         @"arrow" : @(NO)},
                       @{@"imgName" : @"icon_about",
                         @"subTitle" : @"",
                         @"title" : @"关于我们",
                         @"rowHeight" : @(45)},
                      ];
//        @{@"imgName" : @"more_setting",
//          @"title" : @"设置",
//          @"rowHeight" : @(51)}
    }
    return _dataArray;
}

@end
